<template>
  <!-- 系统管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="任务名称:" prop="taskName">
            <el-input
              v-model.trim="filterForm.taskName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入任务名称"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="网址名称:" prop="urlName">
            <el-input
              v-model.trim="filterForm.urlName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入网址名称"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="启动状态:" prop="status">
            <el-select v-model.trim="filterForm.status" placeholder="请选择" :clearable="true">
              <el-option
                v-for="item in [{value: 1,label:'启动'}, {value: 0,label:'未启动'}]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始执行时间:" prop="times">
            <el-date-picker
              v-model="filterForm.times"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-button type="primary" @click="$_handleFilter">查询</el-button>
          <el-button @click="$_handleReset">重置</el-button>
        </el-form>

      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['COLLECTIONRULES_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            v-permission="['COLLECTIONRULES_CARRYOUT_LOG_BUTTON']"
            icon="el-icon-folder-add"
            type="primary"
            @click="goto('ExecutionLog')"
          >
            执行日志列表
          </el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="MX_listLoading"
          :data="MX_list"
          border
          highlight-current-row
          :row-key="$_getRowKey"
          style="width: 100%;text-align:center"
          :header-cell-style="MX_headerCellStyle"
        >
          <template slot="empty">
            <p>暂无数据!</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            align="center"
            :index="$_tableIndex"
          />
          <el-table-column
            v-for="item in columns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :min-width="item.minWidth"
            :formatter="item.formatter"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            fixed="right"
            label="操作"
            width="220px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="tBtn"
                @click="handleDetail(scope.row)"
              >详情</el-button>
              <el-button
                v-permission="['INVESTMENTACTIVITY_UPDATE_BUTTON']"
                size="mini"
                class="tBtn"
                @click="handleEdit(scope.row)"
              >修改</el-button>
              <el-button
                v-permission="['INVESTMENTACTIVITY_DEL_BUTTON']"
                size="mini"
                type="danger"
                class="tBtn"
                @click="handleDelete(scope.row)"
              >删除</el-button>
              <el-button
                v-permission="['COLLECTIONRULES_CARRYOUT_LOG_BUTTON']"
                size="mini"
                class="tBtn"
                @click="goto(`ExecutionLog?id=${scope.row[idKeyName]}`)"
              >执行日志</el-button>
              <el-button
                v-permission="['COLLECTIONRULES_CARRYOUT_BUTTON']"
                size="mini"
                class="tBtn"
                type="primary"
                @click="handleZx(scope.row[idKeyName])"
              >立即执行</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="MX_total > 0"
          :total="MX_total"
          :page.sync="MX_pageNav.pageNo"
          :limit.sync="MX_pageNav.pageSize"
          @pagination="getList"
        />
      </div>
      <DialogForm ref="dialogForm" labelWidth="140px" :formDesignList="formDesignList" :otherParams="otherParams">
        <template slot="other">
          <el-form ref="formRef" :model="otherParams" label-width="140px" label-position="left">
            <template v-for="item in otherFormDesignList">
              <el-form-item v-if="item.prop === 'intervalStep' && [3, 4].includes(otherParams.timeType)"
                            class="inlineFormItem" :label="item.label" :prop="item.prop"
                            :rules="['detail'].includes(MX_dialogType) ? [] : item.rules">
                <FormTemplate :form-item="{...item, dictOptions: otherParams.timeType === 3 ? weekList : dayList}" v-model="otherParams[item.prop]"/>
              </el-form-item>
              <el-form-item v-else-if="item.prop !== 'intervalStep'" :label="item.label" :prop="item.prop" :rules="['detail'].includes(MX_dialogType) ? [] : item.rules">
                <FormTemplate :form-item="item" v-model="otherParams[item.prop]"/>
              </el-form-item>
            </template>
          </el-form>
        </template>
      </DialogForm>
    </div>
  </div>
</template>
<script>
import DialogForm from '@/views/investment/components/DialogForm'
import commonList from "@/utils/mixins/investment/commonList";
import dataCaptureApi from "@/api/investment/dataCapture";
import FormTemplate from '@/views/investment/components/FormTemplate'
import { parseTime } from "@/framework/utils/date";

export default {
  name: 'CollectionRules',
  components: {
    DialogForm,
    FormTemplate
  },
  mixins: [commonList],
  data() {
    let week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    return {
      filterForm: {
        taskName: '',
        urlName: '',
        status: '',
        times: ''
      },
      // 列信息
      columns: [
        { prop: 'taskName', label: `任务名称`, minWidth: '180px' },
        { prop: 'urlName', label: `网址名称`, minWidth: '180px' },
        { prop: 'urlDetil', label: `网址地址`, minWidth: '200px' },
        { prop: 'isRepeat', label: `是否重复`, width: '120px', formatter: function(row) {
            return row.isRepeat === 1 ? '是' : '否'
          } },
        { prop: 'timeType', label: `定时类型`, width: '120px', formatter: function(row) {
            let tText = '';
            switch (row.timeType){
              case 1:
                tText = '时间'
                break;
              case 2:
                tText = '天'
                break;
              case 3:
                tText = '周'
                break;
              case 4:
                tText = '月'
                break;
            }
            return tText
          } },
        { prop: 'status', label: `启动状态`, width: '120px', formatter: function(row) {
            return row.status === 1 ? '启动' : '未启动'
          } },
        { prop: 'startTime', label: `开始执行时间`, width: '180px', formatter: function(row) {
            return !!row.startTime ? parseTime(new Date(row.startTime)) : ''
          } },
        { prop: 'createTime', label: `创建时间`, width: '180px', formatter: function(row) {
            return !!row.createTime ? parseTime(new Date(row.createTime)) : ''
          } }
      ],
      formDesignList: [
        { type: 'text', prop: 'taskName', label: `任务名称`, rules: [{ required: true, message: '请输入任务名称', trigger: 'blur' }] },
        { type: 'text', prop: 'urlName', label: `网址名称`, rules: [{ required: true, message: '请输入网址名称', trigger: 'blur' }] },
        { type: 'textarea', prop: 'urlDetil', label: `网址地址`, maxlength: 500, autosize: {minRows: 5, maxRows: 10}, rules: [{ required: true, message: '请输入网址地址', trigger: 'blur' }] },
        { type: 'text', prop: 'companyNameLabel', label: `企业名称标签`, rules: [{ required: true, message: '请输入企业名称标签', trigger: 'blur' }] },
        { type: 'switch', prop: 'status', label: `启用状态`, onVal: 1, offVal: 0, defaultVal: 0, rules: [{ required: true, message: '请选择启用状态', trigger: 'change' }] },
        { type: 'radioGroup', prop: 'isRepeat', label: `是否重复`, options: [{value: 1,label:'重复'}, {value: 0,label:'不重复'}], defaultVal: 1, rules: [{ required: true, message: '请选择是否重复', trigger: 'change' }] },
      ],
      idKeyName: 'id',
      otherParams: {timeType: 1},
      otherFormDesignList: [
        { type: 'radioGroup', prop: 'timeType', label: `定时类型`, options: [{value: 1,label:'时间'}, {value: 2,label:'天'}, {value: 3,label:'周'}, {value: 4,label:'月'}], rules: [{ required: true, message: '请选择定时类型', trigger: 'change' }] },
        { type: 'select', prop: 'intervalStep', label: `选择时间`, dictOptions: [], rules: [{ required: true, message: '请选择', trigger: 'change' }] },
        { type: 'time', prop: 'intervalTime', label: `选择时间`, format: 'mm:ss', rules: [{ required: true, message: '请选择选择时间', trigger: 'blur' }] },
        { type: 'datetime', prop: 'startTime', label: `开始执行时间`, format: 'yyyy-MM-dd HH:mm:ss', rules: [{ required: true, message: '请选择开始执行时间', trigger: 'blur' }] },
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      weekList: Array.from({length: 7}, (o,v) => ({value: v+1+'', label: week[v]})),
      dayList: Array.from({length: 15}, (o,v) => ({value: v+1+'', label: v+1}))
    }
  },
  watch: {
    'filterForm.times'(val){
      this.$set(this.filterForm, 'start', !!val ? val[0] : '')
      this.$set(this.filterForm, 'end', !!val ? val[1] : '')
    },
    'otherParams.timeType'(val){
      this.$set(this.otherParams, 'intervalTime', '')
      this.$set(this.otherFormDesignList[2], 'format', val === 1 ? 'mm:ss' : 'HH:mm:ss')
      if (val === 3 && this.otherParams.intervalStep > 7){
        this.$set(this.otherParams, 'intervalStep', '1')
      }
    }
  },
  created() {
    this.getList()
  },
  activated() {
  },
  methods: {
    // 获取页面列表
    getList() {
      let filterForm = JSON.parse(JSON.stringify(this.filterForm))
      delete filterForm.times
      this.MX_listLoading = true
      dataCaptureApi.getCJRoulesList({
        ...filterForm,
        ...this.MX_pageNav
      }).then((res) => {
        this.MX_listLength = res.data.records.length
        this.MX_list = res.data.records
        this.MX_total = parseInt(res.data.total || '0')
        this.MX_listLoading = false
      })
    },
    handleDetail(data){
      this.setOtherParams(data)
      this.$_handleDetail(data)
    },
    // 编辑按钮
    handleEdit(data) {
      this.setOtherParams(data)
      this.$refs.dialogForm.open('update', dataCaptureApi.editCJRoulesItem, data || this.MX_applicationMsg)
    },
    // 添加按钮
    handleAdd() {
      this.otherParams = {timeType: 1}
      this.$refs.dialogForm.open('add', dataCaptureApi.addCJRoulesItem)
    },
    // 删除按钮
    handleDelete(data) {
      if (data.status === 1){
        this.$dtMessage({type: 'error', message: '当前任务处于启动状态中，不可删除！'})
        return
      }
      this.$_handleDelete(dataCaptureApi.delCJRoulesItem, data[this.idKeyName], `${this.idKeyName}`)
    },
    setOtherParams(data){
      this.otherParams = {
        timeType: data.timeType,
        intervalStep: data.intervalStep,
        intervalTime: data.intervalTime,
        startTime: data.startTime
      }
    },
    goto(url){
      this.$router.push(`/investment/dataCapture/${url}`)
    },
    handleZx(id){
      const loading = this.$loading({
        lock: true, text: ``, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'
      })
      dataCaptureApi.zxCJRoulesItem({ id }).then((res) => {
        loading.close()
        if (res.code == '00000') {
          this.$dtMessage({
            type: 'success',
            message: '执行成功'
          })
        }else{
          this.$dtMessage({
            type: 'error',
            message: res.message || '执行失败'
          })
        }
      }).catch(res => {
        loading.close()
        this.$dtMessage({
          type: 'error',
          message: '执行失败'
        })
      })
    },
    otherParamsCheck(){
      let flag = true
      this.$refs.formRef.validate((valid) => {
        flag = valid
      })
      console.log(flag)
      return flag
    }
  }
}
</script>

<style lang="scss" scoped>
.tBtn{
  margin-top: 3px;
  margin-bottom: 3px;
}
</style>
